<?php
class Admin_Model_Account extends Zend_Db_Table{

	protected $_name = 'tblUser';
	protected $_primary = 'Id';

	private $USER_TABLE = 'tblUser';
	private $USER_EMAIL = "Email";
	private $USER_PWD = "Password";
	private  $ADMIN = 1;

	protected $db;
	protected  $auth;

	public function __construct(){
		$this->auth = Zend_Auth::getInstance();
		//Goi ket noi voi Zend Db
		$this->db = Zend_Registry::get('connectDB');
	}

	protected $_messageError = null;

	public function hasIdentity() {
		if($this->auth->hasIdentity())
			return true;
		else
			return false;
	}

	public function login($arrParam,$options = null){
		try {
			// Khai bao bang va 2 cot se su dung so sanh trong qua tronh login
			$authAdapter = new Zend_Auth_Adapter_DbTable($this->db);
			$authAdapter->setTableName($this->USER_TABLE)
			->setIdentityColumn($this->USER_EMAIL)
			->setCredentialColumn($this->USER_PWD);
			$select = $authAdapter->getDbSelect();
			$select->where('status = 1');

			$user_name = $arrParam['email'];
			$password = $arrParam['password'];
			$authAdapter->setIdentity($user_name);
			$authAdapter->setCredential(md5($password));

			//Lay ket qua truy van cua Zend_Auth
			$result = $this->auth->authenticate($authAdapter);

			$flag = false;
			if(!$result->isValid()){
				$error = $result->getMessages();
				$this->_messageError = current($error);
			}else{
				//Lay nhung du lieu can thiet trong bang users neu login thanh cong
				$omitColumns = array('password');
				$data = $authAdapter->getResultRowObject(null,$omitColumns);
				//Luu  nhung du lieu cua member vao session
				$this->auth->getStorage()->write($data);
				$flag = true;
			}
			return $flag;
		} catch (Exception $e) {
			echo $e->getTraceAsString();
		}
	}

	public function getError(){
		return $this->_messageError;
	}

	public function logout($arrParam = null,$options = null){
		$this->auth->clearIdentity();
	}

	public function isAdmin(){
		if($this->auth->hasIdentity()) {
			$iRole = $this->auth->getIdentity()->Role;
			if($iRole == $this->ADMIN)
				return true;
			else
				return false;
		}
	}
	public function getName() {
		 if($this->auth->hasIdentity()){
		 	return $this->auth->getIdentity()->Name;
		 }
	}
}